package com.mego.tzadd.activitys;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mego.tzadd.R;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.HttpRequest;
import com.mego.tzadd.utils.NotificationUtil;

import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.JSON;

public class MyService extends Service {
    private final static String TAG = MyService.class.getSimpleName();
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                Log.e(TAG, "" + System.currentTimeMillis());
                try {
                    Thread.sleep(60000);
                    getsns();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 测试线程，判断Service是否在工作
        new Thread(mRunnable).start();
        // 设置为前台进程，降低oom_adj，提高进程优先级，提高存活机率
        return START_STICKY;
    }

    private void getsns() {
        long adminid = SystemCenter.getInstance().adminid;
        if (adminid < 1) {
            return;
        }
        try {
            HttpRequest.getsns(adminid, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject a = jsonArray.getJSONObject(i);
                            notifymsg(a.getString("content"));
                        }
                    }
                }
            });
        } catch (Exception e1) {
        }

    }

    void notifymsg(String msginfo) {
        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), msginfo);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}

